package org.java.auth.config;

import org.java.auth.handler.SmartHandler;
import org.java.auth.service.RemoteUserDetailsService;
import org.java.commons.vo.Result;
import org.java.user.api.PasswordEncoderConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
// 导入加密配置
@Import(PasswordEncoderConfig.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

//      有三种configure方式
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
//    }

    //     配置HTTP协议相关的安全选项，主要包括表单登录、登录结果
    @Override
    public void configure(WebSecurity web) throws Exception {
//        不需要授权
        web.ignoring().mvcMatchers("/css/**", "/js/**", "/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login", "/logout","/user-info").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .usernameParameter("loginName")
                .passwordParameter("password")
                .loginPage("/login")
                .loginProcessingUrl("/do-login")
                .failureHandler(new SmartHandler())
                .successHandler(new SmartHandler())
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new SmartHandler("/error"))
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login") {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
                            throws IOException, ServletException {
                        SmartHandler handler = new SmartHandler();
                        Result result = Result.error("还未登录");
                        if (!handler.sendJson(result, request, response)) {
                            super.commence(request, response, authException);
                        }
                    }
                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/logout-success")
                .and().csrf().disable()
        ;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login")//是URL路径，就是http://localhost:8080/test
                .setViewName("login");//是你HTML或JSP页面名称   test.html或test.jsp。
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        return new RemoteUserDetailsService();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

}
